package com.剑指offer.第六章;

import java.util.Stack;

/**
 * 使用栈 数据结构
 */
public class 后缀表达式 {

    public static Integer resolve(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            switch (token) {
                case "+":
                case "-":
                case "/":
                case "*":
                    Integer pop = stack.pop();
                    Integer pop1 = stack.pop();
                    stack.push(cal(pop1, pop, token));
                    break;
                default:
                    stack.push(Integer.parseInt(token));
            }
        }
        return stack.pop();
    }

    public static Integer cal(Integer a1, Integer a2, String operator) {
        switch (operator) {
            case "+":
                return a1 + a2;
            case "-":
                return a1 - a2;
            case "/":
                return a1 / a2;
            case "*":
                return a1 * a2;
            default:
                return 0;
        }
    }

    public static void main(String[] args) {
        String[] strings = new String[5];
        strings[0] = "2";
        strings[1] = "3";
        strings[2] = "1";
        strings[3] = "*";
        strings[4] = "+";
        System.out.println(resolve(strings));
    }

}
